import {
  checkBillCategory,
  checkPersonBillCreator,
  checkPersonCategoryCreator,
  checkPersonCategoryNameExist,
  queryCheckId
} from "./utils.js";
import billDao from "../Dao/bill.js";
import {httpResult} from "../utils/utils.js";
import categoryDao from "../Dao/category.js";
import sequelize from "../models/init.js";

// 添加新的个人账单
export const addPersonalBill = async (req, res) => {
  let {id, category, remark, amount, isComplete, billTime} = req.body;
  await queryCheckId(id);
  await checkBillCategory(category);
  // 添加账单
  let addRes = await billDao.createPersonalBill(category, remark, amount, id, isComplete, billTime);
  res.json(httpResult.success({result:true, bill:addRes}));
};

// 获取个人账单
export const getPersonalBill = async (req, res) => {
  let {id} = req.body;
  await queryCheckId(id);
  let bills = await billDao.getUserPersonalBills(id);
  res.json(httpResult.success({result: true, bills}));
};

// 删除个人账单
export const deletePersonalBill = async (req, res) => {
  let {id, billId} = req.body;
  await queryCheckId(id);
  await checkPersonBillCreator(id, billId);
  await billDao.deleteBill(billId);
  res.json(httpResult.success({result: true}));
};

// 修改个人账单
export const updatePersonalBill = async (req, res) => {
  let {id, billId, category, remark, amount, isComplete, billTime} = req.body;
  await queryCheckId(id);
  await checkPersonBillCreator(id, billId);
  const t = await sequelize.transaction();
  let bill = {};
  try{
    await billDao.updatePersonalBill(billId, category, remark, amount, isComplete, billTime, t);
    bill = await billDao.getBillById(billId, t);
    await t.commit();
  } catch (e) {
    await t.rollback();
    throw new Error(e.message);
  }
  res.json(httpResult.success({result: true, bill: bill}));
};

// 获取个人账单分类
export const getPersonalBillCategory = async (req, res) => {
  let {id} = req.body;
  await queryCheckId(id);
  let categories = await categoryDao.getUserCategory(id);
  res.json(httpResult.success({result: true, categories}));
};

// 增加个人账单分类
export const addPersonalBillCategory = async (req, res) => {
  let {id, name, is_out} = req.body;
  await queryCheckId(id);
  await checkPersonCategoryNameExist(name, id);
  let addRes = await categoryDao.addUserCategory(name, id, is_out);
  res.json(httpResult.success({result: true, category: addRes}));
};

// 删除个人账单分类
export const deletePersonalBillCategory = async (req, res) => {
  let {id, categoryId} = req.body;
  await queryCheckId(id);
  await checkPersonCategoryCreator(id, categoryId);
  await categoryDao.deleteCategory(categoryId);
  res.json(httpResult.success({result: true}));
};
